package com.example.androidmainshixun.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.example.androidmainshixun.R;
import com.example.androidmainshixun.entity.Goods;

import java.util.List;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private List<Goods> mList;

    public RecyclerAdapter(List<Goods> list){
        mList = list;
    }

    public void updateData(List<Goods> list) {
        mList.clear();
        mList = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.goods_item, null);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }


    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Goods goods = mList.get(position);
        holder.textView1.setText(goods.getName());
        holder.textView2.setText("$ " + goods.getPrice() + "/" );
        holder.photo.setImageResource(goods.getImageResourceId()); // 设置图片
    }



    @Override
    public int getItemCount() {
        return mList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView photo;
        TextView textView1;
        TextView textView2;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            photo = itemView.findViewById(R.id.goods_photo);
            textView1 = itemView.findViewById(R.id.goods_name);
            textView2 = itemView.findViewById(R.id.goods_price);
        }
    }
}

